package com.weizhizs.assistant.code.template;

import com.weizhizs.assistant.code.PropCodeGenerator;
import com.weizhizs.assistant.code.helper.FileHelper;
import com.weizhizs.assistant.code.vo.EnumVO;
import com.weizhizs.assistant.code.vo.TableVO;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class PropVelocityGenerator implements PropCodeGenerator {

    @Override
    public void run(List<EnumVO> enumVOS, List<TableVO> tableVOS) {
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        String langName = "zh_CN";

        //获取模板列表
        Map<String, PropDataLoador> templateMap = PropDataRegister.templateDataMap();
        for (String template : templateMap.keySet()) {
            PropDataLoador templateData = templateMap.get(template);
            Map<String, Object> dataMap = templateData.getDataMap(enumVOS,tableVOS);
            if (null != dataMap) {
                VelocityContext context = new VelocityContext(dataMap);

                //渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(templateData.getTemplateName(), "UTF-8");
                tpl.merge(context, sw);

                FileHelper.saveToFile(templateData.getFileOutPath(), sw.toString(), templateData.getFileName(langName));
            }
        }
    }
}
